package com.hxkcloud.patient.activitys;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hxkcloud.patient.R;
import com.hxkcloud.patient.adapter.InspectionReportAdapter;
import com.hxkcloud.patient.beans.InspectionReportBean;
import com.hxkcloud.patient.beans.InspectionReportWholeBean;
import com.hxkcloud.patient.beans.LastReportMonthBean;
import com.hxkcloud.patient.popup.DateYMPopWindow;
import com.hxkcloud.patient.recorder.MediaManger;
import com.hxkcloud.patient.request.MessageCode;
import com.hxkcloud.patient.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.patient.utils.ImageVideoUtils;
import com.hxkcloud.patient.views.ListDividerItemDecoration;
import com.hxkcloud.patient.views.pulltorefreshlayout.PullToRefreshLayout;
import com.hxkcloud.patient.views.pulltorefreshlayout.PullableRecyclerView;

import java.io.Serializable;
import java.util.Date;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

/**
 * Created by william_sun on 2016-07-14.
 * Description:我的检查报告列表
 */
public class InspectionReportActivity extends BaseActivity implements View.OnClickListener, PullToRefreshLayout.OnRefreshListener {

    //title
    private LinearLayout ll_title;
    private ImageView iv_back;
    private TextView tv_title;
    private ImageView iv_add;

    private TextView dateTV;

    private PullToRefreshLayout refreshLayout;
    private PullableRecyclerView recyclerView;

    private List<InspectionReportBean> datas;
    private InspectionReportAdapter adapter;

    private DateYMPopWindow datetimeSelect;

    private LinearLayout nodataLayout;
    private LinearLayout infoLayout;

    private LinearLayout dateLayout;

    private int voicePosition;

    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {
            case MessageCode.NETWORKCODE_MYINSPECTIONREPORT_SUCCESS:
                refreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
                datas = ((InspectionReportWholeBean) msg.obj).getInspectionReportList();
                if (datas.size() > 0) {
                    nodataLayout.setVisibility(View.GONE);
                    infoLayout.setVisibility(View.VISIBLE);
                    dateLayout.setVisibility(View.VISIBLE);
                    dateTV.setVisibility(View.VISIBLE);
                    adapter.setData(datas);
                } else {
                    nodataLayout.setVisibility(View.VISIBLE);
                    infoLayout.setVisibility(View.GONE);
                    dateLayout.setVisibility(View.VISIBLE);
                    dateTV.setVisibility(View.VISIBLE);
                }

                break;
            case MessageCode.NETWORKCODE_MYINSPECTIONREPORT_FAILURE:
                refreshLayout.refreshFinish(PullToRefreshLayout.FAIL);
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                    return;
                } else {
                    toastMsg(getResources().getString(R.string.inspectionreportfail));
                }
                break;
            case MessageCode.NETWORKCODE_DOWNLOADVOICE_SUCCESS:
//                File file = (File) msg.obj;
                if (!MediaManger.isPlaying()) {
                    datas.get(voicePosition).setIsVoicePlaying(true);
                    adapter.notifyItemChanged(voicePosition);
//                    adapter.setData(datas);
                    MediaManger.playSound(ImageVideoUtils.getDataCacheDir(mContext) + "/voice.amr", new MediaPlayer.OnCompletionListener() {
                        @Override
                        public void onCompletion(MediaPlayer mp) {
                            datas.get(voicePosition).setIsVoicePlaying(false);
//                            adapter.setData(datas);
                            adapter.notifyItemChanged(voicePosition);
                        }
                    });
                }
                break;
            case MessageCode.NETWORKCODE_DOWNLOADVOICE_FAILURE:
                toastMsg(getResources().getString(R.string.voicedownloadfail));
                break;
            case MessageCode.NETWORKCODE_LASTINSPECTIONREPORTMONTH_SUCCESS:
                LastReportMonthBean monthBean = (LastReportMonthBean) msg.obj;
                loading();

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
                String date = sdf.format(new Date(Long.valueOf(monthBean.getMonth())));

                dateTV.setText(date);

                YiJiaHuNetWorkUtils.MyInspectionReport(loginInfo.getUserId(), monthBean.getMonth(), handler);
                break;
            case MessageCode.NETWORKCODE_LASTINSPECTIONREPORTMONTH_FAILURE:
                if (msg.obj != null) {
                    toastMsg((String) msg.obj);
                } else {
                    toastMsg(R.string.datagetfail);
                }
                nodataLayout.setVisibility(View.VISIBLE);
                infoLayout.setVisibility(View.GONE);
                dateLayout.setVisibility(View.VISIBLE);
                dateTV.setVisibility(View.VISIBLE);
                break;
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_inspectionreport);

        datas = new ArrayList<>();

        initView();
        initListener();

    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }

    @Override
    protected void initView() {
        ll_title = (LinearLayout) findViewById(R.id.ll_title);
        iv_back = (ImageView) findViewById(R.id.iv_title_back);
        tv_title = (TextView) findViewById(R.id.tv_title_title);
        iv_add = (ImageView) findViewById(R.id.iv_title_func);

        dateTV = (TextView) findViewById(R.id.tv_inspectionreport_date);

        refreshLayout = (PullToRefreshLayout) findViewById(R.id.refreshlayout_inspectionreport);
        recyclerView = (PullableRecyclerView) findViewById(R.id.recyclerview_inspectionreport);
        recyclerView.setCanLoadMore(false);
        recyclerView.setCanRefresh(true);

        setTitlePadding(ll_title);
        iv_back.setVisibility(View.VISIBLE);
        tv_title.setText(getResources().getText(R.string.inspectionreport));
        iv_add.setVisibility(View.VISIBLE);
        iv_add.setImageResource(R.drawable.nav_add);
        iv_back.setOnClickListener(this);
        iv_add.setOnClickListener(this);

        Calendar cal = Calendar.getInstance();
        int month = cal.get(Calendar.MONTH) + 1;
        int year = cal.get(Calendar.YEAR);
        dateTV.setText(year + "-" + month);
        dateTV.setVisibility(View.GONE);//默认先隐藏

        LinearLayoutManager mLayoutManager = new LinearLayoutManager(mContext);
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(mLayoutManager);
        refreshLayout.setOnRefreshListener(this);

        adapter = new InspectionReportAdapter(mContext, datas, screenWidth, new InspectionReportAdapter.reportListener() {
            @Override
            public void onModify(int position) {
                Intent iModify = new Intent(mContext, AddInspectionReportActivity.class);
                iModify.putExtra("report", (Serializable) datas.get(position));
                startActivityForResult(iModify, 50);
            }

            @Override
            public void onImgShow(int position, int index) {
                Intent iPhotos = new Intent(mContext, PhotosActivity.class);
                iPhotos.putExtra("index", index);
                iPhotos.putExtra("canDel", false);
                iPhotos.putStringArrayListExtra("urls", datas.get(position).getImage());
                startActivity(iPhotos);
            }

            @Override
            public void onVoice(int position) {
                if (!MediaManger.isPlaying()) {
                    String url = datas.get(position).getVoice().replace(".amr.mp3", ".amr");
                    YiJiaHuNetWorkUtils.downloadFile(url, mContext, handler);
                    voicePosition = position;
                }
            }
        });
        recyclerView.setAdapter(adapter);
        recyclerView.addItemDecoration(new ListDividerItemDecoration(this,
                ListDividerItemDecoration.VERTICAL_LIST));

        datetimeSelect = new DateYMPopWindow(this);
        datetimeSelect.setTimeListener(new DateYMPopWindow.TimeListener() {
            @Override
            public void setTime(String time) {
                String timeStr = "";
                if (time.contains(".")) {
                    timeStr = time.replace(".", "-");
                }
                dateTV.setText(timeStr);

                loading();
                long month = 0;
                try {
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M");
                    Date date = sdf.parse(dateTV.getText().toString().toString());
                    month = date.getTime();
                } catch (ParseException e) {

                }
                YiJiaHuNetWorkUtils.MyInspectionReport(loginInfo.getUserId(), month + "", handler);
            }
        });


        nodataLayout = (LinearLayout) findViewById(R.id.ll_report_empty);
        infoLayout = (LinearLayout) findViewById(R.id.ll_report_info);

        dateLayout = (LinearLayout) findViewById(R.id.layout_inspectionreport_date);

    }

    @Override
    protected void initListener() {
        dateTV.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        loading();
//        long month = 0;
//        try {
//            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
//            Date date = sdf.parse(dateTV.getText().toString().toString());
//            month = date.getTime();
//        } catch (ParseException e) {
//
//        }
//        YiJiaHuNetWorkUtils.MyInspectionReport(loginInfo.getUserId(), month + "", handler);
        YiJiaHuNetWorkUtils.getLastReportMonth(handler);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_title_back:
                finish();
                break;
            case R.id.iv_title_func:
                Intent iAdd = new Intent(mContext, AddInspectionReportActivity.class);
                startActivityForResult(iAdd, 50);
                break;
            case R.id.tv_inspectionreport_date:
                datetimeSelect.show(ll_title);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 50) {
                String date = data.getStringExtra("date");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M");
                String month = sdf.format(new Date(Long.valueOf(date)));
                long monthL = 0;
                try {
                    monthL = sdf.parse(month).getTime();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                dateTV.setText(month);
                YiJiaHuNetWorkUtils.MyInspectionReport(loginInfo.getUserId(), monthL + "", handler);
            }
        }
    }

    @Override
    public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
//        refreshLayout.refreshFinish(PullToRefreshLayout.SUCCEED);
        loading();
        long month = 0;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-M");
            Date date = sdf.parse(dateTV.getText().toString().toString());
            month = date.getTime();
        } catch (ParseException e) {

        }
        YiJiaHuNetWorkUtils.MyInspectionReport(loginInfo.getUserId(), month + "", handler);
    }


    @Override
    public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {
        refreshLayout.loadmoreFinish(PullToRefreshLayout.SUCCEED);
    }
}
